import { log } from '@/libs/message'
import { nextTick, ref } from 'vue'

type T_TopMessageInfo = {
  type: string
  text: string | number
  duration?: number
}

/** 顶部消息队列 */
const topMessageList: T_TopMessageInfo[] = []
/** 当前消息 */
const curTopMessage = ref<T_TopMessageInfo>()

let timeout: any = null

/**
 * 顶部消息方法
 */
const topMessage = {
  /** 是否存在实例 */
  ready: 0,

  /**
   * 设置顶部消息
   * @param immediately 是否立即生效
   */
  async set(immediately = true) {
    if (!this.ready || !topMessageList.length || (!immediately && curTopMessage.value)) {
      return
    }

    if (timeout) {
      clearTimeout(timeout)
      timeout = null
      curTopMessage.value = undefined
    }

    await nextTick()

    curTopMessage.value = topMessageList.shift()

    timeout = setTimeout(() => {
      timeout = null
      curTopMessage.value = undefined

      nextTick(this.set.bind(this))
    }, curTopMessage.value?.duration || 4000)
  },

  /**
   * 设置顶部消息
   * @param msg 消息
   * @param immediately 是否立即生效
   */
  push(msg: T_TopMessageInfo, immediately = true) {
    immediately ? topMessageList.unshift(msg) : topMessageList.push(msg)
    this.set(immediately)
  },

  /**
   * 设置顶部消息 - 错误
   * @param text 消息内容
   * @param immediately 是否立即生效
   * @param duration 持续时间
   */
  success(text: string | number, immediately = true, duration = 4000) {
    this.push({ type: 'success', text, duration }, immediately)
  },

  /**
   * 设置顶部消息 - 错误
   * @param text 消息内容
   * @param immediately 是否立即生效
   * @param duration 持续时间
   */
  error(text: string | number, immediately = true, duration = 4000) {
    log([text], 'error')
    this.push({ type: 'error', text, duration }, immediately)
  },

  /**
   * 设置顶部消息 - 错误
   * @param text 消息内容
   * @param immediately 是否立即生效
   * @param duration 持续时间
   */
  warn(text: string | number, immediately = true, duration = 4000) {
    this.push({ type: 'warn', text, duration }, immediately)
  },

  /**
   * 设置顶部消息 - 信息
   * @param text 消息内容
   * @param immediately 是否立即生效
   * @param duration 持续时间
   */
  info(text: string | number, immediately = true, duration = 4000) {
    this.push({ type: '', text, duration }, immediately)
  },

  /**
   * 设置顶部消息 - 信息
   * @param text 消息内容
   * @param immediately 是否立即生效
   * @param duration 持续时间
   */
  system(text: string | number, immediately = true, duration = 4000) {
    this.push({ type: 'system', text, duration }, immediately)
  },

  /**
   * 开发提示
   */
  dev() {
    this.warn('正在种蒜，即将上线')
  },
}

/**
 * 清空顶部消息
 */
const clearTopMsg = () => {
  timeout && clearTimeout(timeout)
  timeout = null
  curTopMessage.value = undefined
  topMessageList.length = 0
}

export { topMessageList, curTopMessage, topMessage, clearTopMsg }
